package com.whj.ems.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.whj.ems.dao.BaseDao;


public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {

	@Autowired
    public void setSessionFactoryOverride(SessionFactory sessionFactory) 
    {   
      super.setSessionFactory(sessionFactory);   
    }     
	
	private Class<T> entityClass;

	@SuppressWarnings("unchecked")
	public BaseDaoImpl(){
		this.entityClass = null;
	    Class c = getClass();
	    Type type = c.getGenericSuperclass();
	    if ((type instanceof ParameterizedType)) {
	      Type[] parameterizedType = ((ParameterizedType)type).getActualTypeArguments();
	      this.entityClass = ((Class)parameterizedType[0]);
	    }
	}
	
	public void delete(T entity) throws Exception {
		this.getHibernateTemplate().delete(entity);
	}

	@SuppressWarnings("unchecked")
	public List<T> get() throws Exception {
		List<T> entitys=new ArrayList<T>();
		entitys=this.getHibernateTemplate().find("from "+this.entityClass.getName());
		return entitys;
	}

	public void save(T entity) throws Exception {
		this.getHibernateTemplate().save(entity);
	}

	public void update(T entity) throws Exception {
		this.getHibernateTemplate().update(entity);
	}
	public T load(int id) throws Exception {
		
		return (T)this.getHibernateTemplate().get(this.entityClass,id);
	}

	@Override
	public void deleteByIds(List<T> entities) throws Exception {
		this.getHibernateTemplate().deleteAll(entities);
	}

	@Override
	public int getCount(Class<T> class1) throws Exception {
		Criteria criteria=this.getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(class1);
		int totalPage = ((Number) criteria.setProjection(
				Projections.rowCount()).uniqueResult())
				.intValue();
		return totalPage;
	}




}
